package bbstorespringmvc.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import bbstorespringmvc.model.Book;

@Repository
@Transactional 
public class BookRepository {
   	@PersistenceContext
    EntityManager em;
   	
	public Book findById(Long id) {

		try { // The JPA API EntityManager.getsingleResult() throws an exception if not found, which is not nice.
			return (Book) em.createQuery("select b from Book b where b.id = :id)")
					.setParameter("id", id)
					.getSingleResult();
		} catch (NoResultException nre) {
			return null;  // Normal, entity is just not found.
		}
	}

	public void persist(Book book){
        em.persist(book);
    }
    
	
	public List<Book> findAllByTitle(){
        return em.createQuery("select b from Book b order by b.title").getResultList();
    }

    public Book findByIsbn(String isbn) {
        return (Book) em.createQuery("select b from Book b where lower(b.isbn) = :isbn").setParameter("isbn", isbn.toLowerCase());
    }

    public Book merge(Book book){
        return em.merge( book );
    }
    
    public void remove(Book book){
        em.remove(book);
    }
}
